package com.seek.util;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class GeocodeUtil {
	public static final String BASE_URL = "http://restapi.amap.com/v3/geocode/geo";
	private static Pattern pattern = Pattern.compile("\"location\":\"(\\d+\\.\\d+),(\\d+\\.\\d+)\"");
	private static final String KEY = "68059bda296cbb5ab25fa2dd42a1e3a9";
	/**
	 * 获取坐标点(经度,纬度)
	 * @return
	 */
	public static String  getLocation(String address){
		String location = "";
		URL myURL = null; 
		HttpURLConnection httpsConn = null;
		InputStreamReader insr = null;
    	BufferedReader br = null;
		try{
			if(CommonUtil.isEmpty(address)){
				return "";
			}
			String url = String .format(BASE_URL+"?address=%s&key=%s", URLEncoder.encode(address,"UTF-8"), KEY);
			myURL = new URL(url);  
	    	httpsConn = (HttpURLConnection) myURL.openConnection();
	    	if (httpsConn != null) { 
	        	insr = new InputStreamReader( httpsConn.getInputStream(), "UTF-8"); 
	        	br = new BufferedReader(insr); 
	        	String data = "";
	        	String line = null; 
	        	while((line= br.readLine())!=null){
	        		data+=line;
	        	} 
	        	Matcher matcher = pattern.matcher(data);  
	            if (matcher.find() && matcher.groupCount() == 2) {  
	                double[] gps = new double[2];  
	                gps[0] = Double.valueOf(matcher.group(1));  
	                gps[1] = Double.valueOf(matcher.group(2));  
	                location = ""+gps[0]+","+gps[1]; 
	            }
	    	}
		}catch(Exception ex){
			ex.printStackTrace();
			return "";
		}finally{
			 try{
				 if(br!=null){
					 br.close();
					 br=null;
				 }
				 if(insr!=null){
					 insr.close();
					 insr=null;
				 }
				 if(httpsConn!=null){
					 httpsConn.disconnect();
					 httpsConn = null;
				 }
			 }catch(IOException ex){
				 ex.printStackTrace();
			 }
		 }
		return location;
	}


	public static void main(String[] args){
		String key = "68059bda296cbb5ab25fa2dd42a1e3a9";
		String address = "北京市朝阳区阜通东大街6号";
		String location = getLocation( address);
		System.out.println(location);
	}

}
